from collections import OrderedDict
from decimal import Decimal

from flask_restful import Resource
from sqlalchemy import and_

from User.models import *
from database import db
from utils import db_util
from flask import request, jsonify
import json, hashlib, uuid
from tokenTest import *

class UserView(Resource):
    # get方法
    @login_required
    def get(self):
        query = db.session().query(HT_UserInfo, HT_RoleInfo.Role_Name, HT_RoleInfo.Role_Type)
        query = query.join(HT_UserAndRole, HT_UserInfo.User_ID == HT_UserAndRole.User_ID) \
            .join(HT_RoleInfo, HT_UserAndRole.Role_ID == HT_RoleInfo.Role_ID).filter(
            HT_RoleInfo.Role_Type == Decimal(1))
        data = query.all()
        for item in data:
            res = item[0].to_json()
            print(item[0].to_json())
            res['roleName'] = item[1]
            return jsonify(res)
        return 'jsonify()'

# 酒店管理员登录接口
class LoginView(Resource):
    def post(self):
        form = json.loads(request.data)
        query = db.session().query(HT_UserInfo, HT_RoleInfo.Role_Name, HT_RoleInfo.Role_Type)
        query = query.join(HT_UserAndRole, HT_UserInfo.User_ID == HT_UserAndRole.User_ID) \
            .join(HT_RoleInfo, HT_UserAndRole.Role_ID == HT_RoleInfo.Role_ID) \
            .filter(and_(HT_RoleInfo.Role_Type == Decimal(1),
                         HT_UserInfo.User_Name == form.get('userName'),
                         HT_UserInfo.User_Password == hashlib.md5(
                             form.get('password').encode(encoding='utf-8')).hexdigest())
                    )
        user = query.first()

        res = {
            'code': 'L001',
            'msg': '登录失败, 用户名或密码错误',
            'data': ''
        }

        if user:
            res['code'] = '0001'
            res['msg'] = '登录成功'
            data = user[0].to_json()
            data['Role_Name'] = user[1]
            data['Role_Type'] = user[2]
            print(data.get('User_ID'))
            query1 = db.session().query(HT_UserInfo.User_ID, HT_UserAndHotel.Hotel_ID)
            query1 = query1.join(HT_UserAndHotel, HT_UserInfo.User_ID == HT_UserAndHotel.User_ID) \
                .filter(HT_UserInfo.User_ID == data.get('User_ID'))
            res1 = query1.first()
            data['Hotel_ID'] = res1[1]

            res['data'] = data
            token = create_token(data.get('User_ID'))
            res['token'] = token

            return jsonify(res)

        return jsonify(res)

# 系统管理员登录接口
class mLoginView(Resource):
    def post(self):
        form = json.loads(request.data)
        query = db.session().query(HT_UserInfo, HT_RoleInfo.Role_Name, HT_RoleInfo.Role_Type)
        query = query.join(HT_UserAndRole, HT_UserInfo.User_ID == HT_UserAndRole.User_ID) \
            .join(HT_RoleInfo, HT_UserAndRole.Role_ID == HT_RoleInfo.Role_ID) \
            .filter(and_(HT_RoleInfo.Role_Type == Decimal(99),
                         HT_UserInfo.User_Name == form.get('userName'),
                         HT_UserInfo.User_Password == hashlib.md5(
                             form.get('password').encode(encoding='utf-8')).hexdigest())
                    )
        user = query.first()

        res = {
            'code': 'L001',
            'msg': '登录失败, 用户名或密码错误',
            'data': ''
        }

        if user:
            res['code'] = '0001'
            res['msg'] = '登录成功'
            data = user[0].to_json()
            data['Role_Name'] = user[1]
            data['Role_Type'] = user[2]
            res['data'] = data
            token = create_token(res.get('User_ID'))
            res['token'] = token
            return jsonify(res)

        return jsonify(res)

# 查询用户
class SearchUserView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        content = form.get('content')
        query = db.session().query(HT_UserInfo, HT_RoleInfo.Role_Name, HT_RoleInfo.Role_Type)
        query = query.join(HT_UserAndRole, HT_UserInfo.User_ID == HT_UserAndRole.User_ID) \
            .join(HT_RoleInfo, HT_UserAndRole.Role_ID == HT_RoleInfo.Role_ID) \
            .filter(and_(HT_RoleInfo.Role_Type == Decimal(1), HT_UserInfo.User_Name.like('%' + content + '%')))
        users = query.all()
        res = {
            'code': '0001',
            'msg': '查询成功',
            'data': []
        }

        for user in users:
            data = user[0].to_json()
            data['Role_Name'] = user[1]
            data['Role_Type'] = user[2]
            res.get('data').append(data)

        return jsonify(res)

# 新增酒店管理员
class InsertUserView(Resource):
    @login_required
    def post(self):
        userId = str(uuid.uuid1())
        userId = ''.join(userId.split('-'))
        form = json.loads(request.data)
        password = hashlib.md5(form.get('userPassword').encode(encoding='utf-8')).hexdigest()
        user = HT_UserInfo(userId, password, form.get('userName'), form.get('userPhone'), Decimal(0))
        db.session.add(user)
        userandhotel = HT_UserAndHotel(userId, form.get('hotelId'))
        db.session.add(userandhotel)
        userandrole = HT_UserAndRole(userId, '909f6f82efe74051ab63ae890e093e2a')
        db.session.add(userandrole)
        db.session.commit()

        res = {
            'code': '0001',
            'msg': '操作成功',
            'data': ''
        }

        return jsonify(res)

# 查询酒店
class SearchHotelView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        content = form.get('content')
        hotels = HT_HotelInfo.query.filter(HT_HotelInfo.Hotel_Name.like('%' + content + '%')).all()

        res = {
            'code': '0001',
            'msg': '查询成功',
            'data': []
        }

        for hotel in hotels:
            res['data'].append(hotel.to_json())

        return jsonify(res)

# 新增酒店
class InsertHotelView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = str(uuid.uuid1())
        hotelId = ''.join(hotelId.split('-'))
        hotel = HT_HotelInfo(hotelId, form.get('hotelName'), form.get('hotelAddress'),
                             form.get('hotelDesc'), form.get('hotelPhone'),
                             form.get('hotelServices'), form.get('hotelLevel'))
        db.session.add(hotel)
        db.session.commit()

        res = {
            'code': '0001',
            'msg': '操作成功',
            'data': ''
        }
        return jsonify(res)

# 修改酒店基本信息
class UpdateHotelView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')
        HT_HotelInfo.query.filter(HT_HotelInfo.Hotel_ID == hotelId).update({
            'Hotel_Name': form.get('hotelName'),
            'Hotel_Address': form.get('hotelAddress'),
            'Hotel_Desc': form.get('hotelDesc'),
            'Hotel_Phone': form.get('hotelPhone'),
            'Hotel_Services': form.get('hotelServices'),
            'Hotel_Level': form.get('hotelLevel')
        })
        db.session.commit()

        res = {
            'code': '0001',
            'msg': '操作成功',
            'data': ''
        }
        return jsonify(res)

# 获取酒店基本信息
class GetHotelView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')
        hotel = HT_HotelInfo.query.get(hotelId)

        res = {'code': '0001', 'msg': '查询成功', 'data': hotel.to_json()}

        return jsonify(res)

# 获取酒店客房信息
class GetHotelRoomView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')
        rooms = HT_RoomInfo.query.filter(HT_RoomInfo.Hotel_ID == hotelId)

        res = {'code': '0001', 'msg': '查询成功', 'data': []}

        for room in rooms:
            res['data'].append(room.to_json())

        return jsonify(res)

# 新增酒店客房类型
class InsertHotelRoomView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')

        hotel = HT_HotelInfo.query.get(hotelId)
        if not hotel:
            res = {'code': 'I001', 'msg': '新增失败，不存在该酒店', 'data': []}
            return jsonify(res)

        roomType = form.get('roomType')
        room = HT_RoomInfo.query.filter(and_(HT_RoomInfo.Hotel_ID == hotelId,
                                             HT_RoomInfo.Room_Type == roomType)).first()
        res = {'code': 'I002', 'msg': '新增失败，已存在相同类型客房', 'data': []}

        if room:
            return jsonify(res)

        room = HT_RoomInfo(hotelId, roomType, form.get('roomPrice'), form.get('roomQuantity'))
        db.session.add(room)
        db.session.commit()

        res = {'code': '0001', 'msg': '新增成功', 'data': []}
        return jsonify(res)

# 修改酒店客房类型
class UpdateHotelRoomView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')
        roomType = form.get('roomType')

        HT_RoomInfo.query.filter(and_(HT_RoomInfo.Hotel_ID == hotelId, HT_RoomInfo.Room_Type == roomType)) \
            .update({
            'Room_Price': form.get('roomPrice'),
            'Room_Quantity': form.get('roomQuantity')
        })

        db.session.commit()
        res = {
            'code': '0001',
            'msg': '操作成功',
            'data': ''
        }
        return jsonify(res)

# 删除酒店客房类型
class DeleteHotelRoomView(Resource):
    @login_required
    def post(self):
        form = json.loads(request.data)
        hotelId = form.get('hotelId')
        roomType = form.get('roomType')

        HT_RoomInfo.query.filter(and_(HT_RoomInfo.Hotel_ID == hotelId, HT_RoomInfo.Room_Type == roomType)).delete()

        db.session.commit()
        res = {
            'code': '0001',
            'msg': '操作成功',
            'data': ''
        }
        return jsonify(res)
